package com.android.music2;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebBrowserActivity extends Activity {

	private static final int MENU_SET_WIKI_URL = 0;
	private static final int MENU_SAVE_WIKI_PAGE_TO_DISK = 1;
	//private static final int MENU_VIEW_CURRENT_WIKI_PAGE = 2;
	private static final int MENU_NEW_SEARCH = 3;
	private static final int MENU_DELETE_SAVED_PAGE = 4;
	private static final int MENU_DELETE_SAVED_URL = 5;
	
	private static final int MENU_SAVE_IMAGE = 5;
	
	//private static final String oldSearchUrl = "http://mobile.wikipedia.org/transcode.php?go=";
	private static final String searchUrl = "http://en.m.wikipedia.org/wiki?search=";
	//private static final String fullSearchUrl = "http://en.wikipedia.org/w/index.php?search=";
	
	private boolean mHasSavedWikiPageOnDisk = false;
	private boolean mHasSavedWikiUrl = false;
	
	private String mSavedWikiUrl = "";
	private WebView mWebView;
	
	private long mAudioId;
	private long mAlbumId;
	private String mArtist;
	private String mTrack;
	private String mAlbum;
	private boolean mIsAlbumSearch;
	
	private boolean mIsViewingLocalFile = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.web_browser);
				
        //Resolve the Intent and retrieve the search criteria
        Bundle extras = getIntent().getExtras();
        mAudioId = extras.getLong("ID");
        mArtist = extras.getString("ARTIST");
        mTrack = extras.getString("TRACK");
        mAlbumId = extras.getLong("ALBUM_ID");
        mIsAlbumSearch = extras.getBoolean("IsAlbum");
        mAlbum = extras.getString("ALBUM");

        mWebView = (WebView) findViewById(R.id.webview);	
        mWebView.setWebViewClient(new MyWebViewClient());
        
        if(mIsAlbumSearch) {
        	//Dont search for "unknown" - better to search for the artist instead
        	if(mAlbum.contains("unknown") || mAlbum.contains("Unknown")) {
        		mAlbum = mArtist;
        	}
    		String url = searchUrl + mAlbum;    	   
    		mWebView.loadUrl(url);
    		setTitle("(Web) Wikipedia - " + mAlbum);
    		mIsViewingLocalFile = false;
        	
        	
        } else {
        
	        //Check for a saved html file
	        String wikiSavedFileLocation = MusicUtils.getSavedWikiFileLocation(this, mAudioId);
	        if(wikiSavedFileLocation == null || wikiSavedFileLocation.length() < 2 ) {
	        	mHasSavedWikiPageOnDisk = false;
	        } else {
	        	mHasSavedWikiPageOnDisk = true;
	        	setTitle("(Saved Page) Wikipedia - " + mArtist + " " + mTrack);        
	        	mWebView.loadUrl("file://" + wikiSavedFileLocation);        
	        	mIsViewingLocalFile = true;
	        }
	        
	    	//Check for a saved url
	        if(!mHasSavedWikiPageOnDisk) {
	        	mSavedWikiUrl = MusicUtils.getSavedWikiUrl(this, mAudioId);
	            if(mSavedWikiUrl == null || mSavedWikiUrl.length() < 2) {
	            	mHasSavedWikiUrl = false;
	            } else {
	            	mHasSavedWikiUrl = true;
	            	setTitle("(Saved Url) Wikipedia - " + mArtist + " " + mTrack);
	            	mWebView.loadUrl(mSavedWikiUrl);   
	            	mIsViewingLocalFile = false;
	            }
	        }
	        
	        //If nothing saved then load the web page
	        if(!mHasSavedWikiPageOnDisk && !mHasSavedWikiUrl) {      	        		        
	        	String url = searchUrl + mArtist + " " + mTrack;	        	    		
	    		mWebView.loadUrl(url);
	    		setTitle("(Web) Wikipedia - " + mArtist + " " + mTrack);
	    		mIsViewingLocalFile = false;
	        }
        }
        
        //Register for context menu so we can save images
        registerForContextMenu(mWebView); 
    
	}
	
	@Override
	public boolean onContextItemSelected (MenuItem item) {
		switch (item.getItemId()) {
			case MENU_SAVE_IMAGE:
    			String fileName = "wimg"+ mAlbumId + ".jpg";
				try {
					getSelectedImage(fileName);
					boolean result = MusicUtils.setAlbumArtworkFile(this, "/sdcard/websave/" + fileName, mAudioId, mAlbumId);
					if(result) {
						Toast.makeText(this, "Image set as album artwork", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(this, "Failed to set as album artwork", Toast.LENGTH_SHORT).show();
					}

				} catch (Exception e) {
					Toast.makeText(this, "Exception setting album artwork", Toast.LENGTH_SHORT).show();
				}
				break;
		}
		return true;
	}

	@Override
	 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { 
		
		HitTestResult result = mWebView.getHitTestResult();
		if (result.getType() == HitTestResult.IMAGE_TYPE || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
			 menu.setHeaderTitle(result.getExtra());         
			 menu.add(0, MENU_SAVE_IMAGE, 0, "Set Image as album artwork");
		}
    
	}
	
    /***
     * Called when the hardware BACK button pressed
     */
	@Override
	public void onBackPressed() {
		setResult(RESULT_OK);
		finish();
		super.onBackPressed();	
	}
	
	@Override 
	public void onConfigurationChanged(Configuration newConfig){             
		super.onConfigurationChanged(newConfig); 
	} 
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, MENU_NEW_SEARCH, 0, R.string.new_wiki_search).setIcon(android.R.drawable.ic_menu_search);
		
		if(!mIsViewingLocalFile)
		{			
			if(mWebView.getUrl() != null) {
				menu.add(0, MENU_SAVE_WIKI_PAGE_TO_DISK, 0, R.string.save_wiki_page).setIcon(android.R.drawable.ic_menu_save);
				menu.add(0, MENU_SET_WIKI_URL, 0, R.string.set_wiki_url).setIcon(android.R.drawable.ic_menu_set_as);
							
			} else {
				Toast.makeText(this, "Loading web page...", Toast.LENGTH_SHORT).show();
			}
		} else {
			menu.add(0, MENU_DELETE_SAVED_PAGE, 0, R.string.delete_wiki_page).setIcon(android.R.drawable.ic_menu_delete);
		}
		if(mHasSavedWikiUrl) {
			menu.add(0, MENU_DELETE_SAVED_URL, 0, R.string.delete_wiki_url).setIcon(android.R.drawable.ic_menu_delete);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	    	case MENU_SET_WIKI_URL: {	    
	    		String url = mWebView.getUrl();
	    		MusicUtils.setSavedWikiUrl(this, url);
	    		Toast.makeText(this, "Set URL: " + url, Toast.LENGTH_SHORT).show();
	    		return true;
	    	}
	    	case MENU_SAVE_WIKI_PAGE_TO_DISK: {
	    		MusicUtils.setSavedWikiUrl(this, mWebView.getUrl());
	    		try {
	    			String fileName = "wiki"+ mAudioId + ".html";
					processHttp(mWebView.getUrl(), fileName);
					Toast.makeText(this, "Saved to: " + "/sdcard/websave/" + fileName, Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					Toast.makeText(this, "Error saving page", Toast.LENGTH_SHORT).show();
				}
	    		
	    		return true;
	    	}
	    	case MENU_NEW_SEARCH: {
	        	String url = searchUrl + mArtist + " " + mTrack;
	        	setTitle("(Web) Wikipedia - " + mArtist + " " + mTrack);
	        	if(mIsAlbumSearch) {
	        		url = searchUrl + mAlbum;
	        		setTitle("(Web) Wikipedia - " + mAlbum);
	        	}
	    		mWebView.loadUrl(url);	    		
	    		return true;
	    	}
	    	case MENU_DELETE_SAVED_PAGE: {

	    		String wikiSavedFileLocation = MusicUtils.getSavedWikiFileLocation(this, mAudioId);
	    		File f = new File(wikiSavedFileLocation);

	    	    // Make sure the file or directory exists and isn't write protected
	    	    if (!f.exists()) {
	    	    	Toast.makeText(this, "Saved page does not exist", Toast.LENGTH_SHORT).show();
	    	    	return true;
	    	    }

	    	    if (!f.canWrite()) {
	    	    	Toast.makeText(this, "Unable to delete file", Toast.LENGTH_SHORT).show();
	    	    	return true;
	    	    }

	    	    // Attempt to delete it
	    	    boolean success = f.delete();
	    	    
	    		//Clear the entry in from the database
	    		MusicUtils.setSavedWikiFileLocation(this, "");

	    	    if (success) {
	    	    	Toast.makeText(this, "Saved page deleted", Toast.LENGTH_SHORT).show();
	    	    } else {
	    	    	Toast.makeText(this, "Failed to delete saved page", Toast.LENGTH_SHORT).show();
	    	    }
	    		return true;
	    	}
	    	case MENU_DELETE_SAVED_URL: {
	    		//Clear the entry in the database
	    		MusicUtils.setSavedWikiUrl(this, "");
	    		Toast.makeText(this, "Saved URL cleared", Toast.LENGTH_SHORT).show();
	    		return true;
	    	}
        }
		return super.onOptionsItemSelected(item);
	}
	

	
	public void processHttp(String url, String saveAs) throws Exception
	{
		//Get the HTML file from the web
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
		String response = httpClient.execute(httpGet, responseHandler);
		File f = new File("/sdcard/websave");
		if (!f.exists()) f.mkdir();
		String fileName = "/sdcard/websave/" + saveAs;
		FileWriter fw = new FileWriter(fileName);
		fw.write(response);
		fw.flush();
		fw.close();
		//Store the file location in our database
		MusicUtils.setSavedWikiFileLocation(this, fileName);
	}
	
	public void getSelectedImage(String fileName) {
		try
		{
			HitTestResult result = mWebView.getHitTestResult(); 
			HttpClient httpclient = new DefaultHttpClient(); 
			HttpGet httpget = new HttpGet(result.getExtra()); 
			HttpResponse response = httpclient.execute(httpget); 
			HttpEntity entity = response.getEntity(); 
			if (entity != null) {        
				//Create a temporary file     
				File tempFile = new File(Environment.getExternalStorageDirectory() + "/websave", fileName);     
				if(!tempFile.exists())             
					tempFile.createNewFile();      
				InputStream instream = entity.getContent();     
				BufferedInputStream bufferedInputStream = new BufferedInputStream(instream);     
				//Read bytes into the buffer     
				ByteArrayBuffer buffer = new ByteArrayBuffer(50);     
				int current = 0;     
				while ((current = bufferedInputStream.read()) != -1) {             
					buffer.append((byte) current);     
				}      
				//Write the buffer to the file     
				FileOutputStream stream = new FileOutputStream(tempFile);     
				stream.write(buffer.toByteArray());     
				stream.close();  
			} 
		}catch (Exception e){		
			Toast.makeText(this, "Failed to get selected image", Toast.LENGTH_SHORT).show();
		}
	}

	private class MyWebViewClient extends WebViewClient {    

		@Override    
		public boolean shouldOverrideUrlLoading(WebView view, String url) {    
			//Do not override; let my WebView load the page   
			return false;  
			}
		}
	
		


}
